/*
 * @Date: 2024-03-29 15:21:27
 * @LastEditors: bingkui.wu
 * @LastEditTime: 2024-04-08 11:01:00
 * @Description: 登录接口
 */
import { REQUEST } from "#type/request";
import Response from "@common/Response";
import { User } from "@models/User";
import * as jwt from "jsonwebtoken";
import { JWT_SECRET_KEY } from "@/config";
import { md5 } from "js-md5";

const root: REQUEST.BASIC = {
  auth: false,
  method: "post",
  request: async (ctx: any) => {
    const { userName, password } = ctx.request.body;
    const encodePassword = md5(password);
    let obj = await User.findOne({ userName }).lean().exec();
    if (!obj) {
      // 不存在，进行注册
      const newUser = {
        userName,
        password: encodePassword,
        nickName: userName,
        createTime: new Date().getTime(),
      };
      obj = await User.create(newUser);
    } else if (encodePassword !== obj.password) {
      // 存在，判断密码
      return Response.Error(401, "密码错误");
    }

    const token = jwt.sign(
      { _id: obj._id, userName: obj.userName, nickName: obj.nickName },
      JWT_SECRET_KEY,
      {
        expiresIn: "365d", // 有效期，测试用。正式使用请修改短一点
      }
    );

    return Response.Success({ token });
  },
};

export default root;
